package com.cafuc.javaEE.filter;


import com.cafuc.javaEE.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginFilter", urlPatterns = {"/*"})
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        //System.out.println("登录验证拦截器。");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset = UTF-8");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String uri = request.getRequestURI();
        if(uri.contains("css") ||uri.contains("login") || uri.contains("register")) chain.doFilter(req, resp);
        else {
            User user = (User) request.getSession().getAttribute("user");
            //System.out.println("user" + user.getUserName());
            if (user == null){
               // request.getRequestDispatcher("WEB-INF/template/account/login.jsp").forward(request, response);
                response.sendRedirect("/login");

            }else {
                chain.doFilter(req, resp);
            }
        }
    }
}
